<?php

namespace App\Model;

use EasySwoole\DDL\Enum\Character;
use EasySwoole\DDL\Enum\Engine;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\ORM\Utility\Schema\Table;
use Throwable;

class ShopGoodSeeModel extends AbstractModel
{
    protected $tableName = 't_shop_goods_see';
    protected $autoTimeStamp = true; // 自动写入create_time和update_time 这两个字段是int

    /**
     * @throws Exception
     * @throws Throwable
     * @throws Exception|Throwable
     */
    public function getGoods($where)
    {
        $where['is_deleted'] = 0;
        return $this->order('id', 'desc')->get($where);
    }

    /**
     * @throws Throwable
     * @throws Exception
     */
    public function addGoods($where)
    {
        try {
            $model = new ShopGoodsModel();
            // 开启事务
            \EasySwoole\ORM\DbManager::getInstance()->startTransaction();

            $this->data($where, false);
            $res = $this->save();

            $upR = [
                'num_read' => QueryBuilder::inc(1),
            ];
            $upRes = ShopGoodsModel::create()->update($upR, ['id' => $where['gid']]);


            // 提交事务
            \EasySwoole\ORM\DbManager::getInstance()->commit();
            return $res;
        } catch (Throwable $e) {
            // 回滚事务
            \EasySwoole\ORM\DbManager::getInstance()->rollback();
            return false;
        }
    }

    public function schemaInfo(bool $isCache = true): Table
    {
        $table = new Table($this->tableName);

        $table->setIfNotExists();
        $table->setTableEngine(Engine::INNODB);
        $table->setTableCharset(Character::UTF8MB4_GENERAL_CI);
        $table->setTableComment('商城-商品-浏览');

        $table->colInt('id')->setIsAutoIncrement()->setIsPrimaryKey(true)->setColumnComment("ID");
        $table->colInt('sid', 25)->setDefaultValue(0)->setIsNotNull()->setColumnComment('商户id');
        $table->colInt('uid', 25)->setDefaultValue(0)->setIsNotNull()->setColumnComment('用户id');
        $table->colVarChar('gid', 20)->setDefaultValue('')->setColumnComment('商品编号');
        $table->colTinyInt('is_deleted', 1)->setDefaultValue(0)->setIsNotNull()->setColumnComment('是否删除：0.未删除，1.已删除');
        $table->colInt('create_time', 10)->setDefaultValue(0)->setIsNotNull()->setColumnComment('创建时间戳');
        $table->colInt('update_time', 10)->setDefaultValue(0)->setIsNotNull()->setColumnComment('更新时间戳');

        $table->indexNormal('idx_shop_goods_gid', 'gid');
        $table->indexNormal('idx_shop_goods_uid', 'uid');
        $table->indexNormal('idx_shop_goods_sid', 'sid');
        $table->indexNormal('idx_shop_goods_deleted', 'is_deleted');
        return $table;
    }
}